package com.hinnotek.warehouse.ui.fragment

import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.TextView
import com.hinnotek.warehouse.R
import com.hinnotek.warehouse.databinding.FragmentMyBinding
import com.hinnotek.warehouse.dialog.Dialogs
import com.hinnotek.warehouse.utils.CustomUpdateParser
import com.lee.common.base.BaseToolbarFragment
import com.lee.common.di.BASE_URL
import com.lee.common.event.MessageEvent
import com.lee.common.event.RESTART_SCAN
import com.lee.common.utils.*
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.grouplist.XUICommonListItemView
import com.xuexiang.xui.widget.grouplist.XUIGroupListView
import com.xuexiang.xupdate.XUpdate
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.text.DecimalFormat

class MyFragment : BaseToolbarFragment<FragmentMyBinding>() {

    private lateinit var mGroupListView1: XUIGroupListView
    private lateinit var mGroupListView2: XUIGroupListView

    private var cacheString: String = ""
    private lateinit var textView: TextView

    override fun getLayoutId(): Int {
        return R.layout.fragment_my
    }

    override fun initData() {

        setTitle("我的")
        hideLiftBack()

        mGroupListView1 = mBinding.groupListView
        mGroupListView2 = mBinding.groupListView2

        val item1 = mGroupListView1.createItemView(getString(R.string.modifyPersonalData))
        item1.accessoryType = XUICommonListItemView.ACCESSORY_TYPE_NONE
        item1.detailText = SharedPreUtils.getString("userName")

        val item2 = mGroupListView1.createItemView(getString(R.string.modifyPass))
        item2.accessoryType = XUICommonListItemView.ACCESSORY_TYPE_CHEVRON
        val item4 = mGroupListView2.createItemView(getString(R.string.cleanCached))
        item4.detailText = ""
        item4.accessoryType = XUICommonListItemView.ACCESSORY_TYPE_CHEVRON
        getApkFileSize(item4.detailTextView.apply {
            textView = this
        })

        XUIGroupListView.newSection(requireContext())
            .setUseTitleViewForSectionSpace(false)
            .addItemView(item1) { startActivity(1) } //
            .addItemView(item2) { startActivity(2) } //
            .addItemView(item4) { startActivity(3) } //
            .addTo(mGroupListView1)

        val item7 = mGroupListView2.createItemView(getString(R.string.about))
        item7.accessoryType = XUICommonListItemView.ACCESSORY_TYPE_CHEVRON

        val item8 = mGroupListView2.createItemView(getString(R.string.versionUp))
        item8.detailText = "V1.0"
        item8.accessoryType = XUICommonListItemView.ACCESSORY_TYPE_CHEVRON


        val item5 = mGroupListView2.createItemView(getString(R.string.feedback))
        item5.accessoryType = XUICommonListItemView.ACCESSORY_TYPE_CHEVRON

        XUIGroupListView.newSection(requireContext())
            .setUseTitleViewForSectionSpace(false)
            .addItemView(item7) { startActivity(4) } //
            .addItemView(item8) { startActivity(5) } //
            .addTo(mGroupListView2)

        mBinding.loginOut.setOnClickListener {
            MaterialDialog.Builder(requireContext())
                .iconRes(com.lee.common.R.drawable.icon_tip)
                .title("提示")
                .content("是否退出登录")
                .positiveText("确定")
                .onPositive { dialog, _ ->
                    dialog.dismiss()
                    SharedPreUtils.setBoolean("isLogin", false)
                    Skipping.start(ACTIVITY_LOGIN_NEW)
                    activity?.finish()

                }
                .negativeText("取消")
                .onNegative { dialog, which ->
                    dialog.dismiss()
                }
                .show()
        }

    }

    private fun startActivity(index: Int) {
        when (index) {
            2 -> {//密码
                Skipping.start(ACTIVITY_MODIFY_PASS)
            }
            3 -> {//缓存
                Dialogs(requireContext()).showCurrency3(
                    "是否清除缓存"
                ) { _, _ -> deleteApkCache() }
            }
            4 -> {//关于
                Skipping.start(ACTIVITY_LOGIN_ABOUT)
            }
            5 -> {//更新
                updateVersion()
            }
        }
    }

    /**
     * 获取缓存大小
     */
    private fun getApkFileSize(text: TextView) {
        AppSizeUtils.getInstance().setDatasListent { cacheSize, dataSize, codeSize ->
            Timber.d(
                "缓存大小: " + size(cacheSize) + " 数据大小: " + size(dataSize) + " 应用大小: " + size(codeSize)
            )
            text.visibility = View.VISIBLE
            text.text = size(cacheSize)
            cacheString = text.text.toString()
        }.init(requireContext())
    }

    private fun updateVersion() {
        val updateUrl = BASE_URL + "app/manage/getNewUpdateVersion"
        XUpdate.newBuild(requireContext())
            .updateUrl(updateUrl)
            .updateParser(CustomUpdateParser())
            .update()
    }

    /**
     * 清除缓存
     */
    private fun deleteApkCache() {
        if (DataCleanManager.cleanInternalCache(requireContext())) {
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                DataCleanManager.cleanInternalExternalCache(requireContext())
            }
            ToastUtils.showLong("清除成功")
            cacheString = ""
            if (::textView.isInitialized)
                textView.text = ""
        } else {
            ToastUtils.showLong("清除失败")
        }
    }

    /**
     * 文件大小转换
     */
    private fun size(size: Long): String {
        return when {
            size / (1024 * 1024 * 1024) > 0 -> {
                val tmpSize = (size) / (1024 * 1024 * 1024).toFloat()
                val df = DecimalFormat("#.##")
                "" + df.format(tmpSize) + "GB"
            }
            size / (1024 * 1024) > 0 -> {
                val tmpSize = (size) / (1024 * 1024).toFloat()
                val df = DecimalFormat("#.##")
                "" + df.format(tmpSize) + "MB"
            }
            size / 1024 > 0 -> "" + (size / (1024)) + "KB"
            else -> "" + size + "B"
        }
    }

}